package 力扣热题100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 合并区间
 */
public class LeetCode26 {
    public static int[][] merge(int[][] intervals) {
        if(intervals.length==0){
            return new int[0][2];
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0]-o2[0];
            }
        });
        List<int[]>arr=new ArrayList<>();
        for (int i = 0; i <intervals.length ; i++) {
            if(arr.size()==0){
                arr.add(new int[]{intervals[0][0],intervals[0][1]});
                continue;
            }
            int k=arr.size();
            if(arr.get(k-1)[1]>intervals[i][1]){
                continue;
            }else if (arr.get(k-1)[1]<=intervals[i][1]&&arr.get(k-1)[1]>=intervals[i][0]){
                arr.get(k-1)[1]=intervals[i][1];
            }else {
                arr.add(new int[]{intervals[i][0],intervals[i][1]});
            }
        }
        return arr.toArray(new int[arr.size()][]);
    }

    public static void main(String[] args) {
        int[][]arr={{1,3},{2,6},{8,10},{15,18}};
        merge(arr);
    }
}
